#include "game_settings.h"

#include "game_screen.h"
#include <dll.h>
#include <log.h>
#include <stdio.h>

////////////////////////////////////////////////////////////////////////////////

bool GameSettings::create()
{
  Dimension screen_dim = Graphics_getScreenDim();
  
  _background = new Background();
  _background->setColour(Colour::GREY);
  
  _panel = new Panel();
  
  _num_players_spin = new SpinBox(4, 2, 4);
  
  for (int i = 0; i < SIM_MAX_PLAYERS; i++)
  {
    _ai_text_field[i] = new TextField();
    
    _panel->add(_ai_text_field[i], 100, 150 + 40 * i);
  }
  
  _start_button = new Button("START");
  _back_button = new Button("BACK");
  
  _panel->add(_num_players_spin, 100, 100);
  _panel->add(_start_button, screen_dim.w - 2 * _start_button->width() - 15,
      screen_dim.h - _start_button->height() - 10);
  _panel->add(_back_button, screen_dim.w - _back_button->width() - 10,
      screen_dim.h - _back_button->height() - 10);
  
  GUI_setBackground(_background);
  GUI_setContent(_panel);
  
  return true;
}

void GameSettings::destroy()
{
  delete _background;
  delete _panel;
  delete _num_players_spin;
  
  for (int i = 0; i < SIM_MAX_PLAYERS; i++)
  {
    delete _ai_text_field[i];
  }
  
  delete _start_button;
  delete _back_button;
}

void GameSettings::handleKeyDown(const GUIKeyDownEvent* event)
{
  if (event->getKey() == KEY_ESCAPE)
  {
    quit();
  }
}

void GameSettings::handleWidgetEvent(const GUIWidgetEvent* event)
{
  if (event->getWidget() == _start_button)
  {
    runGame();
  }
  else if (event->getWidget() == _back_button)
  {  
    quit();
  }
  else if (event->getWidget() == _num_players_spin)
  {
    for (int i = 0; i < SIM_MAX_PLAYERS; i++)
    {
      _ai_text_field[i]->setEnabled(i < _num_players_spin->value());
    }
  }
}

void GameSettings::runGame()
{
  DLL dll[SIM_MAX_PLAYERS];
  AICreateFunc ai_create_func[SIM_MAX_PLAYERS];
  AI* ai[SIM_MAX_PLAYERS];
  char filename[256];
  bool success = true;
  
  for (int i = 0; i < _num_players_spin->value(); i++)
  {
    sprintf(filename, "ai\\%s.dll", _ai_text_field[i]->text());
    
    dll[i] = DLL_load(filename);
    if (!dll[i])
    {
      success = false;
      break;
    }
    
    ai_create_func[i] = (AICreateFunc)DLL_loadFunc(dll[i], "AI_create");
    if (!ai_create_func[i])
    {
      success = false;
      break;
    }
    
    ai[i] = ai_create_func[i]();
    if (!ai[i])
    {
      success = false;
      break;
    }
  }
  
  if (!success)
  {
    return;
  }
  
  GameScreen* game_screen =
    new GameScreen(_num_players_spin->value(), ai);
  
  GUI_runState(game_screen);
  
  delete game_screen;
  
  for (int i = 0; i < _num_players_spin->value(); i++)
  {
    DLL_free(dll[i]);
  }
}
